﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpEchoServer
{
    private  UdpClient _udpClient;
    private  IPEndPoint _listenEndPoint;

    public UdpEchoServer(int port)
    {
        _listenEndPoint = new IPEndPoint(IPAddress.Any, port);
        _udpClient = new UdpClient(_listenEndPoint);
    }

    public void Start()
    {
        Console.WriteLine("UDP Echo Server is running...");
        _udpClient.BeginReceive(AsyncReceiveCallback, null);
    }

    private void AsyncReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Receive the data from the client
            byte[] receiveBytes = _udpClient.EndReceive(ar, ref _listenEndPoint);
            string receiveString = Encoding.ASCII.GetString(receiveBytes);

            Console.WriteLine("Received: {0}", receiveString);

            // Echo the data back to the client
            byte[] sendBytes = Encoding.ASCII.GetBytes(receiveString);
            _udpClient.BeginSend(sendBytes, sendBytes.Length, _listenEndPoint, AsyncSendCallback, null);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            // Listen for the next client
            _udpClient.BeginReceive(AsyncReceiveCallback, null);
        }
    }

    private void AsyncSendCallback(IAsyncResult ar)
    {
        // Signals the UdpClient that the asynchronous operation has completed
        _udpClient.EndSend(ar);
    }
}